const { default: axios } = require("axios");
const { encrypt, decrypt } = require("../util/Sm4Helper");
const { v4: uuidv4 } = require("uuid");
const { sm3 } = require("sm-crypto");
const returnString = require('../util/returnstring');

const neusoft_host = "http://10.10.76.79:8888/health/v1/nurse";

const appType = "33";
const signingKey = "a703c139da79b1768e72cc9d49f4725c";
let nonce = "";
let timestamp;
const messageType = "99";
const messageId = 718;

function setNonceAndTime() {
  nonce = uuidv4();
  timestamp = Date.now();
}

/**
 * 使用 sm3 签名
 * @param {*} body 请求 body 体
 * @returns
 */
function getSignature(body) {
  let salt = nonce.substring(timestamp % 10);
  const signature = sm3(signingKey + nonce + salt + sm3(body));
  return signature;
}

/**
 * 使用 sm4 给 body 体加密，用于接口的请求体
 * @param {*} body
 * @returns
 */
function getSm4Body(body) {
  const jsonString = JSON.stringify(body);
  return encrypt(jsonString, signingKey);
}

async function getAllDataByPaperNos(params) {
  setNonceAndTime();

  // let req = {
  //   paperNoList: ["210282198601032317"],
  //   page: {
  //     current: 1,
  //     size: 10,
  //     total: 100,
  //   },
  // };

  let req = {
    paperNoList: params["paperNoList"],
    page: {
      current: params["current"] ? params["current"] : 1,
      size: params["size"] ? params["size"] : 10,
      total: params["total"] ? params["total"] : 100,
    },
  };

  const url = neusoft_host + "/getAllDataByPaperNos";
  // Headers for the request
  const headers = {
    "Content-Type": "application/json",
    accept: "*/*",
    appType: appType,
    signature: getSignature(JSON.stringify(req)),
    timestamp: timestamp.toString(),
    nonce,
    params:JSON.stringify(req)
  };

  let obj = {
    requestData: encrypt(JSON.stringify(req), signingKey),
  };

  try {
    let resObj = await axios.post(url, obj, { headers });
    return decrypt(resObj.data.responseData, signingKey);
  } catch(error) {
    console.error("Error:", error.message);
    return {};
  }
  
}

/**
 * 给手环发送消息
 * @param {*} value
 */
async function pushAcMessage(value) {
  setNonceAndTime();

  let pars = {
    messageId: generateRandomNumbers(),
    title: value.title,
    content: value.content,
  };

  if (value.dcIds) {
    pars.dcIds = value.dcIds;
  }

  let req = {
    messageType,
    data: [pars],
  };

  const url = neusoft_host + "/pushAcMessage";
  // Headers for the request
  const headers = {
    "Content-Type": "application/json",
    accept: "*/*",
    appType: appType,
    signature: getSignature(JSON.stringify(req)),
    timestamp: timestamp.toString(),
    nonce,
  };

  let obj = {
    requestData: getSm4Body(req),
  };

  const sendInfoResult = await axios
    .post(url, obj, { headers })
    .then((response) => {
      const responseString = decrypt(response.data.responseData, signingKey);
      const returnObj = JSON.parse(responseString);
      return JSON.parse(returnString(1, returnObj.data, returnObj.msg));
    })
    .catch((error) => {
      // Handle error
      console.error("pushAcMessage Error:", error.message);
      return JSON.parse(returnString(-1, [], error.message));
    });
    console.log(sendInfoResult);
    return sendInfoResult;
}

function generateRandomNumbers() {
  const min = 1;
  const max = 1000;
  const numberOfNumbers = 1000;

  const randomNumbers = Array.from(
    { length: numberOfNumbers },
    () => Math.floor(Math.random() * (max - min + 1)) + min
  );

  returnNum = Math.floor(Math.random() * (max - min + 1)) + min;

  return returnNum;
}

exports.getAllDataByPaperNos = getAllDataByPaperNos;
exports.pushAcMessage = pushAcMessage;
